<?php 
/**
 * 
 * @author shitou
 *
 */
class OrderModel extends Model {
	
	/**
	 * 添加商品到订单
	 */
	public function addDihses($val,$flag,$orderno){
		
		$ids = explode(',', $val);
		if(empty($ids)){
			return array('info'=>'请选择需要加入订单的商品'); 
		}
		
		foreach($ids as $k=>$v){
			
			$model  = M('OrderDetail');
			$module = M('Dishes');
			$detail = $module->find($v);
			
			$where['pid']     = $v;
			$where['orderno'] = $orderno;
			$one    = $model->where($where)->find();
			$order  = M('Order')->where("orderno='$orderno'")->find();
			
			/*if($one['id']){
				$data = $model->where($where)->setInc('amount');
				$data = $model->where($where)->setInc('total',$one['price']);
			}else{*/
				$rows['pid']     = $v;
				$rows['pno']     = $detail['dishes_num'];
				$rows['title']   = $detail['title'];
				$rows['entitle'] = $detail['entitle'];
				$rows['price']   = $detail['sprice'];
				$rows['mprice']  = $detail['mprice'];
				$rows['tprice']  = $detail['sprice'];
				$rows['dprice']  = $detail['sprice'];
				$rows['total']   = $detail['sprice'];
				$rows['tableid'] = $order['tableid'];
				$rows['dataid']  = $order['dataid'];
				$rows['outletid']= $order['outletid'];
				$rows['orderno'] = $orderno;
				$rows['flag']    = 'dishes';
				$rows['amount']  = 1;
				$rows['addtime'] = time();
				
				$data = $model->add($rows);
			//}
		}
		
		if($data){
			return array('status'=>1,'data'=>$rows);
		}else{
			return array('info'=>'添加商品到订单失败，请稍后重试!');
		}
	}

	/**
	 * 添加饮品到订单
	 */
	public function addDrink($val,$flag,$orderno){
	
		$ids = explode(',', $val);
		if(empty($ids)){
			return array('info'=>'请选择需要加入订单的商品');
		}
	
		foreach($ids as $k=>$v){
				
			$model  = M('OrderDetail');
			$module = M('Drink');
			$detail = $module->find($v);
				
			$where['pid']     = $v;
			$where['orderno'] = $orderno;
			$one    = $model->where($where)->find();
			$order  = M('Order')->where("orderno='$orderno'")->find();
				
			if($one['id']){
				$data = $model->where($where)->setInc('amount');
				$data = $model->where($where)->setInc('total',$one['price']);
			}else{
				$rows['pid']     = $v;
				$rows['pno']     = $detail['drink_num'];
				$rows['title']   = $detail['title'];
				$rows['entitle'] = $detail['entitle'];
				$rows['price']   = $detail['sprice'];
				$rows['mprice']  = $detail['mprice'];
				$rows['tprice']  = $detail['sprice'];
				$rows['dprice']  = $detail['sprice'];
				$rows['total']   = $detail['sprice'];
				$rows['tableid'] = $order['tableid'];
				$rows['dataid']  = $order['dataid'];
				$rows['outletid']= $order['outletid'];
				$rows['orderno'] = $orderno;
				$rows['flag']    = 'drink';
				$rows['amount']  = 1;
				$rows['addtime'] = time();
	
				$data = $model->add($rows);
			}
		}
	
		if($data){
			return array('status'=>1,'data'=>$rows);
		}else{
			return array('info'=>'添加商品到订单失败，请稍后重试!');
		}
	}
	
	/**
	 * 发送短信
	 */
	public function sendSms($map){
	
		$model = M("Admin");
		$view  = $model->find($map['dealid']);  //用户详情
	
		//$msg = "有新的订单分配到您,请及时处理！";
		//$msg = "【订单号：".$map['orderno']."】有新的订单分配到您,请及时处理！";
		$bian = ",http://kkrabbit.com.cn/mdmin.php【KKR订单分配信息】";
		$msg  = "有新的订单分配：【".$bian."】。如需帮助请联系客服。";
	
		$map['mobile']   = $view['mobile'];
		$map['content']  = $msg;
		return sendRest("RMS/Sms/single",$map);
	}
	
	/**
	 * 获取指定商品的详情
	 * @param unknown_type $array
	 * @param unknown_type $pid
	 * @return Ambigous <string, unknown>
	 */
	public function getProductAttr($array,$pid) {
		
		$detail = "";
		
		foreach($array as $k=>$v){
			if($v['pid']==$pid){
				$detail = $v;
				$detail['attr'] = json_decode($v['attr'],true);
				break;
			}
		}
		return $detail;
	}
	
	/**
	 * 计算开始时间和技术时间
	 */
	public function getStartEndTime($m){
		
		$start = "";
		$end   = "";
		$date  = "";
		if($m['year']&&$m['mouth']&&$m['day']){
			$date  = $m['year'].'-'.$m['mouth'].'-'.$m['day'];
			$start = strtotime($date." 00:00:00");
			$end   = strtotime($date." 23:59:59");
		}elseif($m['year']&&$m['mouth']){
			$date  = $m['year'].'-'.$m['mouth'];
			$start = strtotime($date.'-'.'01');
			$end   = strtotime($date.'-'.'31');
		}elseif($m['mouth']&&$m['day']){
			$date  = $m['mouth'].'-'.$m['day'];
			$start = strtotime($m['year'].'-'.$date." 00:00:00");
			$end   = strtotime($m['year'].'-'.$date." 23:59:59");
		}elseif($m['year']){
			$date  = $m['year'];
			$start = strtotime($date."-01-01");
			$end   = strtotime($date."-12-31");
		}elseif($m['mouth']){
			$date  = $m['mouth'];
			$start = strtotime($m['year'].'-'.$date."-01");
			$end   = strtotime($m['year'].'-'.$date,"-31");
		}elseif($m['day']){
			$date  = $m['day'];
			$start = strtotime($m['year'].'-'.$m['mouth'].'-'.$date." 00:00:00");
			$end   = strtotime($m['year'].'-'.$m['mouth'].'-'.$date." 23:59:59");
		}
		
		$map['start'] = $start;
		$map['end']   = $end;
		
		return $map;
	}
	
	public function getFormatNumber($num){
		$arr = explode('.',$num);
		
		$b = mb_substr($arr[1],0,2);
		if(empty($b)){
			$b = "00";
		}
		return $arr[0].'.'.$b;
	}
	
	/**
	 * 根据订单列表，获取销售数据
	 */
	public function getSellTotal($list){
		

		$map['to_totalfee']   = 0;  //订单总菜品金额
		$map['to_dishesfee']  = 0;  //订单总菜品金额
		$map['to_shipfee']    = 0;  //订单总服务金额
		$map['to_drinkfee']   = 0;  //订单总酒水金额
		$map['to_orderfee']   = 0;  //订单支付总金额
		$map['to_settlefee']  = 0;  //订单总结算金额
		$map['to_receivefee'] = 0;  //订单总实收金额
		
		foreach($list as $k=>$v){

			$map['to_totalfee']   += $v['orderfee'];  //订单总菜品金额
			$map['to_dishesfee']  += $v['dishesfee'];  //订单总菜品金额
			$map['to_shipfee']    += $v['shipfee'];  //订单总服务金额
			$map['to_drinkfee']   += $v['drinkfee'];  //订单总酒水金额
			$map['to_orderfee']   += $v['orderfee'];  //订单总金额
			$map['to_settlefee']  += $v['settlefee'];  //订单总结算金额
			$map['to_receivefee'] += $v['receivefee'];  //订单总实收金额
			
		}
		return $map;
	}
	
	/**
	 * 根据订单列表，获取销售数据
	 */
	public function getStatusTotal($list){
		
		$map['toorder']    = 0;  //订单总数
		$map['toStatus1']  = 0;  //未确认订单总数
		$map['toStatus2']  = 0;  //已确认订单总数
		$map['toStatus3']  = 0;  //已分配订单总数
		$map['toStatus4']  = 0;  //到达餐厅订单总数
		$map['toStatus5']  = 0;  //配货完成订单总数
		$map['toStatus6']  = 0;  //已签收订单订单总数
		$map['toStatus7']  = 0;  //客户拒签订单总数
	
		foreach($list as $k=>$v){
			
			$map['toorder']        ++;  //订单总数
				
			if($v['status']==1){
				$map['toStatus1']  ++;  //未确认订单总数
			}
			if($v['status']==2){
				$map['toStatus2']  ++;  //已确认订单总数
			}
			if($v['status']==3){
				$map['toStatus3']  ++;  //已分配订单总数
			}
			if($v['status']==4){
				$map['toStatus4']  ++;  //到达餐厅订单总数
			}
			if($v['status']==5){
				$map['toStatus5']  ++;  //配货完成订单总数
			}
			if($v['status']==6){
				$map['toStatus6']  ++;  //已签收订单订单总数
			}
			if($v['status']==7){
				$map['toStatus7']  ++;  //客户拒签订单总数
			}
		}
		return $map;
	}
	/**
	 * 根据订单列表，获取配送统计数据
	 */
	public function getDeliveryTotal($list,$dealid){

		$map['sendNum']     = 0;   //配送员送单数
		$map['receivables'] = 0;   //配送员收款数
		
		foreach($list as $k=>$v){
			if($dealid){
				if($v['dealid']==$dealid){
					$map['sendNum']     ++;
					$map['receivables'] += $v['totalfee'];
				}
			}else{
				$map['sendNum']     = 0;   //配送员送单数
				$map['receivables'] = 0;   //配送员收款数
			}
		}
		
		return $map;
	}
	
	/**
	 * 检索配送员
	 */
	public function checkDelivery($list,$data){
		
		foreach($list as $k=>$v){
			foreach($data as $m=>$n){
				if($v['dealid']==$n['id']){
					$list[$k]['dealname'] = $n['realname'];
				}
			}
		}
		
		return $list;
	}
	
	/**
	 * 
	 */
	public function export($list){
		
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=订单表格".date("Y-m-d").".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		$tag0  = iconv("UTF-8", "GB2312",'订单编号');
		$tag13  = iconv("UTF-8", "GB2312",'餐厅名称');
		$tag1  = iconv("UTF-8", "GB2312",'状态');
		$tag2  = iconv("UTF-8", "GB2312",'配送员');
		$tag3  = iconv("UTF-8", "GB2312",'订购者');
		$tag4  = iconv("UTF-8", "GB2312",'联系电话');
		$tag5  = iconv("UTF-8", "GB2312",'订单金额');
		$tag6  = iconv("UTF-8", "GB2312",'酒水金额');
		$tag7  = iconv("UTF-8", "GB2312",'服务金额');
		$tag8  = iconv("UTF-8", "GB2312",'优惠金额');
		$tag9  = iconv("UTF-8", "GB2312",'总金额');
		$tag10 = iconv("UTF-8", "GB2312",'调整费');
		$tag11 = iconv("UTF-8", "GB2312",'实收金额');
		$tag12 = iconv("UTF-8", "GB2312",'需要发票');
		$tag13 = iconv("UTF-8", "GB2312",'与客户确认');
		$tag14 = iconv("UTF-8", "GB2312",'下单时间');
		$tag15 = iconv("UTF-8", "GB2312",'酒水饮料');
		
		echo "$tag0\t$tag13\t$tag1\t$tag2\t$tag3\t$tag4\t$tag5\t$tag6\t$tag7\t$tag8\t$tag9\t$tag10\t$tag11\t$tag12\t$tag13\t$tag14\t$tag15\n";
		
		$drink = C("IS_SEND_DRINK");
		foreach($list as $key=>$val){
			
			if($val['outletid']){
				$outlet   = M('Outlet')->where("id='".$val['outletid']."'")->field('title')->find();
				$outtitle = $outlet['title'];
			}
			
			$orderno   = iconv("UTF-8", "GB2312", $val['orderno']);
			$outtitle  = iconv("UTF-8", "GB2312", $outtitle);
			$status    = iconv("UTF-8", "GB2312", get_array_key("ORDER_STATUS",$val['status']));
			$dealid    = iconv("UTF-8", "GB2312", $val['realname']);
			$username  = iconv("UTF-8", "GB2312", $val['username']);
			$mobile    = iconv("UTF-8", "GB2312", $val['mobile']);
			$dishesfee = iconv("UTF-8", "GB2312", $val['dishesfee']);
			$drinkfee  = iconv("UTF-8", "GB2312", $val['drinkfee']);
			$shipfee   = iconv("UTF-8", "GB2312", $val['shipfee']);
			$cardfee   = iconv("UTF-8", "GB2312", $val['cardfee']);
			$orderfee  = iconv("UTF-8", "GB2312", $val['orderfee']);
			$b_price   = iconv("UTF-8", "GB2312", $val['b_price']);
			$totalfee  = iconv("UTF-8", "GB2312", $val['orderfee']+$val['b_price']);
			$isinvoice = iconv("UTF-8", "GB2312", $val['isinvoice']==1?"是":"否");
			$isconfirm = iconv("UTF-8", "GB2312", $val['isconfirm']==1?"是":"否");
			$addtime   = iconv("UTF-8", "GB2312", date("Y-m-d H:i:s",$val['addtime']));

			//酒水资料
			$html   = ""; 
			$detail = M('OrderDetail')->where(array('orderno'=>$val['orderno']))->select();
			if($val['isdrink']>0){
				$html  .= "免费赠送饮料：".$drink[$val['isdrink']]['zh-cn'].'、';
			}
			foreach($detail as $k=>$v){
				if($v['flag'] == 'drink'){
					$html .= "客人购买：".$v['title']."(".$v['amount'].")、";
				}	
			}
			$drinks = iconv("UTF-8", "GB2312", $html);
			
			echo "$orderno\t$outtitle\t$status\t$dealid\t$username\t$mobile\t$dishesfee\t$drinkfee\t$shipfee\t$cardfee\t$orderfee\t$b_price\t$totalfee\t$isinvoice\t$isconfirm\t$addtime\t$drinks\n";
		}
	}
	
	//导出财务报表
	public function exportCaiwu($list){
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=餐厅结算金额统计表格".date("Y-m-d").".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		$tag0   = iconv("UTF-8", "GB2312",'订单编号');
		$tag1   = iconv("UTF-8", "GB2312",'餐厅名称');
		$tag2   = iconv("UTF-8", "GB2312",'订单日期');
		$tag3   = iconv("UTF-8", "GB2312",'餐厅金额');
		$tag4   = iconv("UTF-8", "GB2312",'订餐金额');
		$tag5   = iconv("UTF-8", "GB2312",'酒水金额');
		$tag6   = iconv("UTF-8", "GB2312",'服务金额');
		$tag7   = iconv("UTF-8", "GB2312",'优惠金额');
		$tag8   = iconv("UTF-8", "GB2312",'调整费');
		$tag9   = iconv("UTF-8", "GB2312",'总金额');
		$tag10  = iconv("UTF-8", "GB2312",'结算金额');
		$tag11  = iconv("UTF-8", "GB2312",'手工结算金额');
		$tag12  = iconv("UTF-8", "GB2312",'利润');
		
		echo "$tag0\t$tag1\t$tag2\t$tag3\t$tag4\t$tag5\t$tag6\t$tag7\t$tag8\t$tag9\t$tag10\t$tag11\t$tag12\n";
		
		$numtotal  = 0;  //订单数
		$outtotal  = 0;  //餐厅金额
		$distotal  = 0;  //订餐金额
		$settotal  = 0;  //结算金额
		$shitotal  = 0;  //服务费
		$bprtotal  = 0;  //调整费
		$cartotal  = 0;  //优惠
		$dritotal  = 0;  //酒水
		$rectotal  = 0;  //利润
		$zontotal  = 0;  //总金额
		
		foreach($list as $key=>$val){
			
			if($val['outletid']){
				$outlet   = M('Outlet')->where("id='".$val['outletid']."'")->field('title')->find();
				$outtitle = $outlet['title'];
			}
			
			$numtotal += 1;
			$outtotal +=$val['dishesfee'];
			$distotal +=$val['dishesfee'];
			$settotal +=$val['settlefee'];
			$shitotal +=$val['shipfee'];
			$bprtotal +=$val['b_price'];
			$cartotal +=$val['cardfee'];
			$dritotal +=$val['drinkfee'];
			$rectotal +=$val['receivefee'];
			$zontotal += $val['orderfee'];
			
			$orderno    = iconv("UTF-8", "GB2312", $val['orderno']);
			$outtitle   = iconv("UTF-8", "GB2312", $outtitle);
			$addtime    = iconv("UTF-8", "GB2312", date('Y-m-d',$val['addtime']));
			$outletfee  = iconv("UTF-8", "GB2312", $val['dishesfee']);
			$dishesfee  = iconv("UTF-8", "GB2312", $val['dishesfee']);
			$drinkfee   = iconv("UTF-8", "GB2312", $val['drinkfee']);
			$shipfee    = iconv("UTF-8", "GB2312", $val['shipfee']);
			$cardfee    = iconv("UTF-8", "GB2312", $val['cardfee']);
			$tianzfee   = iconv("UTF-8", "GB2312", $val['b_price']);
			$orderfee   = iconv("UTF-8", "GB2312", $val['orderfee']);
			$settlefee  = iconv("UTF-8", "GB2312", $val['settlefee']);
			$rsettlefee = iconv("UTF-8", "GB2312", $val['rsettlefee']);
			$receivefee = iconv("UTF-8", "GB2312", $val['receivefee']);
			
			echo "$orderno\t$outtitle\t$addtime\t$outletfee\t$dishesfee\t$drinkfee\t$shipfee\t$cardfee\t$tianzfee\t$orderfee\t$settlefee\t$rsettlefee\t$receivefee\n";
		}
		$ordernum = iconv("UTF-8", "GB2312", '订单数量');
		echo "$ordernum\t\t$numtotal\t$outtotal\t$distotal\t$dritotal\t$shitotal\t$cartotal\t$bprtotal\t$zontotal\t$settotal\t\t$rectotal\n";
	}
	
	/**
	 * 导出订单时间报表
	 */
	public function export_time($list,$user){
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=快递配送报表".date("Y-m-d").".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		$tag0  = iconv("UTF-8", "GB2312",'序号');
		$tag1  = iconv("UTF-8", "GB2312",'日期');
		$tag2  = iconv("UTF-8", "GB2312",'餐厅');
		$tag3  = iconv("UTF-8", "GB2312",'客户地址');
		$tag4  = iconv("UTF-8", "GB2312",'订单金额');
		$tag5  = iconv("UTF-8", "GB2312",'服务费');
		$tag6  = iconv("UTF-8", "GB2312",'订单总价');
		$tag7  = iconv("UTF-8", "GB2312",'结算金额');
		$tag8  = iconv("UTF-8", "GB2312",'实收金额');
		$tag9  = iconv("UTF-8", "GB2312",'下单时间');
		$tag10 = iconv("UTF-8", "GB2312",'收单时间');
		$tag11 = iconv("UTF-8", "GB2312",'取餐时间');
		$tag12 = iconv("UTF-8", "GB2312",'送达时间');
		$tag13 = iconv("UTF-8", "GB2312",'客服用时');
		$tag14 = iconv("UTF-8", "GB2312",'餐厅用时');
		$tag15 = iconv("UTF-8", "GB2312",'快递用时');
		$tag16 = iconv("UTF-8", "GB2312",'实际用时');
		$tag17 = iconv("UTF-8", "GB2312",'快递员');
		$tag18 = iconv("UTF-8", "GB2312",'备注');
		
		echo "$tag0\t$tag1\t$tag2\t$tag3\t$tag4\t$tag5\t$tag6\t$tag7\t$tag8\t$tag9\t$tag10\t$tag11\t$tag12\t$tag13\t$tag14\t$tag15\t$tag16\t$tag17\t$tag18\n";
		
		
		foreach($user as $m=>$n){
			$i     = 1;
			$count = 0;
			foreach($list as $k=>$val){
				if($val['dealid']==$n['id']){
					
					//客户地址
					if($val['cnaddress']){
						$address = $val['cnaddress'];
					}else{
						$address = $val['address'];
					}
					
					$outletName  = M('Outlet')->find($val['outletid']);
					$key	     = iconv("UTF-8", "GB2312", $i);
					$orderdate   = iconv("UTF-8", "GB2312", date('ymd',$val['addtime']));
					$outlet      = iconv("UTF-8", "GB2312", $outletName['title']);
					$address     = iconv("UTF-8", "GB2312", $address);
					$dishesfee   = iconv("UTF-8", "GB2312", round($val['dishesfee']+$val['drinkfee']));
					$shipfee    = iconv("UTF-8", "GB2312",  round($val['shipfee']+$val['exemptfee']));
					$orderfee    = iconv("UTF-8", "GB2312", round($val['orderfee']));
					$settlefee   = iconv("UTF-8", "GB2312", round($val['settlefee']));
					$receivefee  = iconv("UTF-8", "GB2312", round($val['receivefee']));
					$ordertime   = iconv("UTF-8", "GB2312", date('H:i',$val['ordertime']));
					$time_que    = iconv("UTF-8", "GB2312", date('H:i',$val['time_que']));
					$time_pei    = iconv("UTF-8", "GB2312", date('H:i',$val['time_pei']));
					$time_shou   = iconv("UTF-8", "GB2312", date('H:i',$val['time_shou']));
					$kefu_time   = iconv("UTF-8", "GB2312", getminus($val['time_que']-$val['ordertime']));
					$cant_time   = iconv("UTF-8", "GB2312", getminus($val['time_pei']-$val['time_que']));
					$kuaidi_time = iconv("UTF-8", "GB2312", getminus($val['time_shou']-$val['time_pei']));
					$shiji_time  = iconv("UTF-8", "GB2312", getminus($val['time_shou']-$val['ordertime']));
					$realname    = iconv("UTF-8", "GB2312", $n['realname']);
					$remark      = iconv("UTF-8", "GB2312", $val['content']);
					
					$i++;
					$count += $val['shipfee']+$val['exemptfee'];
					echo "$key\t$orderdate\t$outlet\t$address\t$dishesfee\t$shipfee\t$orderfee\t$settlefee\t$receivefee\t$ordertime\t$time_que\t$time_pei\t$time_shou\t$kefu_time\t$cant_time\t$kuaidi_time\t$shiji_time\t$realname\t$remark\n";
				}
			}
			if($count>0){
				echo "\t\t\t\t\t$count\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n";
			}
		}
	}
	
	/**
	 * 导出订单销售报表
	 */
	public function export_sell($list){
		
		//饮品数组
		$drinkArr = C("IS_SEND_DRINK");
		
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=订单销售报表".date("Y-m-d").".xls");
		header("Pragma: no-cache");
		header("Expires: 0");
		
		$tag0  = iconv("UTF-8", "GB2312",'序号');
		$tag1  = iconv("UTF-8", "GB2312",'日期');
		$tag2  = iconv("UTF-8", "GB2312",'餐厅');
		$tag3  = iconv("UTF-8", "GB2312",'客户地址');
		$tag4  = iconv("UTF-8", "GB2312",'订餐金额');
		$tag5  = iconv("UTF-8", "GB2312",'酒水饮料');
		$tag6  = iconv("UTF-8", "GB2312",'服务费');
		$tag7  = iconv("UTF-8", "GB2312",'总金额');
		$tag8  = iconv("UTF-8", "GB2312",'结算金额');
		$tag9  = iconv("UTF-8", "GB2312",'实收金额');
		$tag10  = iconv("UTF-8", "GB2312",'接单时间');
		$tag11  = iconv("UTF-8", "GB2312",'收单时间');
		$tag12  = iconv("UTF-8", "GB2312",'取餐时间');
		$tag13  = iconv("UTF-8", "GB2312",'送达时间');
		$tag14  = iconv("UTF-8", "GB2312",'客服用时');
		$tag15  = iconv("UTF-8", "GB2312",'餐厅用时');
		$tag16  = iconv("UTF-8", "GB2312",'快递用时');
		$tag17  = iconv("UTF-8", "GB2312",'实际用时');
		$tag18  = iconv("UTF-8", "GB2312",'配送员');
		$tag19  = iconv("UTF-8", "GB2312",'备注');
		
		echo "$tag0\t$tag1\t$tag2\t$tag3\t$tag4\t$tag5\t$tag6\t$tag7\t$tag8\t$tag9\t$tag10\t$tag11\t$tag12\t$tag13\t$tag14\t$tag15\t$tag16\t$tag17\t$tag18\t$tag19\n";
		
		$i = 1;
		foreach($list as $key=>$val){
			
			//查询配送员
			if($val['dealid']){
				$view = M("Admin")->find($val['dealid']);
				$realname = $view['realname'];
			}
			
			//查询餐厅名称
			$outletName = M('Outlet')->find($val['outletid']);
			
			//客户地址
			if($val['cnaddress']){
				$address = $val['cnaddress'];
			}else{
				$address = $val['address'];
			}
			
			$key	     = iconv("UTF-8", "GB2312", $i);
			$orderdate   = iconv("UTF-8", "GB2312", date('ymd',$val['addtime']));
			$outlet      = iconv("UTF-8", "GB2312", $outletName['title']);
			$address     = iconv("UTF-8", "GB2312", $address);
			$dishesfee   = iconv("UTF-8", "GB2312", round($val['dishesfee']));
			$drinkfee    = iconv("UTF-8", "GB2312", round($val['drinkfee']));
			$servfee     = iconv("UTF-8", "GB2312", round($val['orderfee']-$val['drinkfee']-$val['dishesfee']));
			$orderfee    = iconv("UTF-8", "GB2312", round($val['orderfee']));
			$settlefee   = iconv("UTF-8", "GB2312", round($val['settlefee']));
			$receivefee  = iconv("UTF-8", "GB2312", round($val['receivefee']));
			$ordertime   = iconv("UTF-8", "GB2312", date('H:i',$val['ordertime']));
			$time_que    = iconv("UTF-8", "GB2312", date('H:i',$val['time_que']));
			$time_pei    = iconv("UTF-8", "GB2312", date('H:i',$val['time_pei']));
			$time_shou   = iconv("UTF-8", "GB2312", date('H:i',$val['time_shou']));
			$kefu_time   = iconv("UTF-8", "GB2312", getminus($val['time_que']-$val['ordertime']));
			$cant_time   = iconv("UTF-8", "GB2312", getminus($val['time_pei']-$val['time_que']));
			$kuaidi_time = iconv("UTF-8", "GB2312", getminus($val['time_shou']-$val['time_pei']));
			$shiji_time  = iconv("UTF-8", "GB2312", getminus($val['time_shou']-$val['ordertime']));
			$realname    = iconv("UTF-8", "GB2312", $realname);
			$remark	     = iconv("UTF-8", "GB2312", '');
			
			$i++;
			echo "$key\t$orderdate\t$outlet\t$address\t$dishesfee\t$drinkfee\t$servfee\t$orderfee\t$settlefee\t$receivefee\t$ordertime\t$time_que\t$time_pei\t$time_shou\t$kefu_time\t$cant_time\t$kuaidi_time\t$shiji_time\t$realname\t$remark\n";
		
			//送饮品
			if($val['isdrink']){
				$exemptfee  = round($exemptfee);
				$outlet     = iconv("UTF-8", "GB2312", 'kk酒水');
				$address    = iconv("UTF-8", "GB2312", '免费送'.$drinkArr[$val['isdrink']]['zh-cn']);
				$drinkfee   = 0;
				$orderfee   = 0;
				$receivefee = 0;
				echo "\t$orderdate\t$outlet\t$address\t\t$drinkfee\t\t$orderfee\t\t$receivefee\t\t\t\t\t\t\t\t\t\t\n";
			}

			//订单备注
			$bak = M('OrderBak')->where('did='.$val['id'])->select();
			if($bak){
				foreach($bak as $k=>$v){
					$receivefee  = $v['price'];
					$opera       = $v['opera']=='minus'?'-':'';
					$receivefee  = $receivefee?$opera.$receivefee:0;
					
					$receivefee  = iconv("UTF-8", "GB2312", $receivefee);
					$address     = iconv("UTF-8", "GB2312", $v['remark']);
					$drinkfee    = 0;
					$orderfee    = 0;
						
					echo "\t$orderdate\t\t$address\t\t$drinkfee\t\t$orderfee\t\t$receivefee\t\t\t\t\t\t\t\t\t\t\n";
				}
			}
			
			//优惠-减免配送费
			if($val['exemptfee']>0){
				$exemptfee  = round($val['exemptfee']);
				$address    = iconv("UTF-8", "GB2312", '优惠');
				$servfee    = iconv("UTF-8", "GB2312", '-'.$exemptfee);
				$receivefee = iconv("UTF-8", "GB2312", '-'.$exemptfee);
				echo "\t$orderdate\t\t$address\t\t\t$servfee\t\t\t$receivefee\t\t\t\t\t\t\t\t\t\t\n";
			}
		}
	}

	//查看菜品属性是否有必选项
	public function checkAttr($gnfr){
		$flag = false;
		$html = "";
		$gnfr = json_decode($gnfr,true);

		foreach($gnfr as $k=>$v){
			if($v['type'] == 1){
				$flag = true;
			}
		}
		if($flag){
			$html = "*";
		}
		return $html;
	}

	
	/**
	 * 获取商品的属性
	 * @param json数组  $gnfr
	 */
	public function getDishesAttr($gnfr){
		
		$i     = 1;
		$html  = "<tr style='display:none'><td colspan='7'>";
		
		foreach($gnfr as $k=>$v){
			$ht    = $i !=1?"<br/>":"";
			$html .= $ht.'<span class="dtitle">'.$v['title'].'：</span>';
			
			foreach($v['config'] as $m=>$n){
				$html .= '<span class="xtitle">'.$n['title'].'('.$n['entitle'].')';
				if($n['num']){
					$html .= '：'.$n['num'].'份';
				}
				if($n['mprice']){
					$html .= '（加￥'.$n['mprice'].'）';
				}
				$html .= '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
			}
			$i++;
		}
		
		$html .= "</td></tr>";
		return $html;
	}
	
	/**
	 * 添加商品到购物车
	 * @param unknown_type $map
	 */
	public function addcart($map){
		
		$arr = explode(',', $map['val']);
		$mem = getMemberSession();
		
		foreach($arr as $k=>$v){
			
			if($map['flag']=='dishes'){
				//查询商品详情
				$one = sendRest('RMS/Product/detail',array('id'=>$v));
				$one = $one['data'];
				
				$row['isspec']   = $one['tprice']==0.00?1:2;                             //是否特价，1是2否
				$row['price']    = $one['tprice']==0.00?$one['sprice']:$one['tprice'];   //菜品价格
				$row['dprice']   = $one['tprice']==0.00?$one['sprice']:$one['tprice'];   //菜品价格   
			}else{
				//查询饮品详情
				$one = sendRest('RMS/Product/drinkDetail',array('id'=>$v));
				$one = $one['data'];
				
				$row['isspec']   = 2;                //是否特价，1是2否
				$row['price']    = $one['sprice'];   //菜品价格
				$row['dprice']   = $one['sprice'];   //菜品价格
			}
			
			$row['id']       = $v;                  //菜品id
			$row['flag']     = $map['flag'];          //商品类型
			$row['solevar']  = create_id();         //唯一标识    
			$row['psPrice']  = 0.00;             
			$row['outletid'] = $map['outletid'];  
 			$row['dataid']   = $mem['dataid'];
 			$row['type']     = $mem['tableid'];  
			$row['gnfr']     = "";
			$row['part']     = "";                                                                                         $row['admin']    = 1; //标识后台添加                                                            
			
			$cart  = sendRest("RMS/Cart/addtoCart", $row,'post');
		}
		return $cart;
	}
	
	/**
	 * 移除数组中的空值
	 * @param  array $array
	 * @return array
	 */
	public function arrray_remove($array){
		foreach ($array as $k=>$v){
			foreach ($v['config'] as $z=>$y){
				foreach($y as $m=>$n){
					if(empty($n)){
						unset($array[$k]["config"][$z][$m]);
					}
				}
				if(empty($array[$k]["config"][$z])){
					unset($array[$k]["config"][$z]);
				}
				if(empty($array[$k]["config"][$z]['title'])){
					unset($array[$k]["config"][$z]);
				}
			}
			if(empty($array[$k]['config'])){
				unset($array[$k]);
			}
		}
		return $array;
	}
	
	/**
	 * 计算所有属性的成本价以及销售价
	 * @param unknown_type $gnfr
	 */
	public function getAttrTotal($gnfr){
		
		$propPrice = 0;
		$psPrice   = 0;
		
		//计算商品和所有属性的价格之和
		foreach ($gnfr as $k=>$v){
			if($v['xtype']==1){
				foreach ($v['config'] as $m=>$n){
					$mprice = $v['config'][$m]['mprice'];
					if($mprice){
						$propPrice += $mprice;
						$psPrice   += $n['psprice'];
					}
				}
			}else{
				foreach ($v['config'] as $m=>$n){
					if($n['mprice']){
						$propPrice += $n['num']*$n['mprice'];
						$psPrice   += $n['num']*$n['psprice'];
					}
				}
			}
		}
		return array('price'=>$propPrice,'psPrice'=>$psPrice);
	}
	
	/**
	 * 判断餐厅是否处于休息时段
	 * @param  array  $v
	 * @return string
	 */
	public function getRestaurantTime($v){
		$css  = "";
		$start1 = strtotime(date('Y-m-d').' '.$v['starthours']);
		$end1   = strtotime(date('Y-m-d').' '.$v['endhours']);
		
		if($v['starthours1'] && $v['endhours1']){
			$start2 = strtotime(date('Y-m-d').' '.$v['starthours1']);
			$end2   = strtotime(date('Y-m-d').' '.$v['endhours1']);
			if(($start2>time()||$end2<time())&&($start1>time()||$end1<time())){
				$css = "background:red;color:#FFF";
			}
		}else{
			if($start1>time()||$end1<time()){
				$css = "background:red;color:#FFF";
			}
		}
		if($v['is_tingye'] == 1){
			$css = "background:grey;color:#FFF";
		}
		return $css;
	}
	
	/**
	 * 获取会员列表
	 * @param unknown_type $data
	 * @return string
	 */
	public function getMemberSelect($data){
		
		$status = 0;
		$html   = "<select name='memberid' id='memberid'><option value=''>请选择会员</option>";
		
		if($data['data']){
			
			$status = 1;
			foreach($data['data'] as $k=>$v){
				$realname = $v['realname']?$v['realname']:"匿名用户";
				//$html    .= "<option value='".$v['id']."'>".$realname."[".$v['mobile']."]</option>";
				$html    .= "<option value='".$v['id']."'>".$realname."</option>";
			}
			$html .= "</select>";
		}else{
			$html = "<span id='memberid' class=''>没有找到相关的会员信息</span><span id='addcustom' class='editbtn'>登记新会员</span>";
		}
		
		$arr['html']   = $html;
		$arr['status'] = $status;
		return $arr;
	}
	
	/**
	 * 获取会员详细资料和会员地址列表
	 * 
	 */
	public function getMemberDetail($id){
		
		//会员详细信息
		$map['memberid'] = $id;
		$data = sendRest('MMS/Custom/view',$map);
		
		//会员地址列表
		$model   = M('Address');
		$address = $model->where('userid='.$id.' and isdel=2')->select();
		
		$html = '<select name="addressid" id="addressid" style="width:200px"><option value="">请选择会员地址</option>';
		foreach($address as $k=>$v){
			$html .= '<option value="'.$v['id'].'">'.$v['address'].'</option>';
		}
		$html .= '</select>';
		
		$arr['data'] = $data['data'];
		$arr['html'] = $html;
		return $arr;
	}
	
	public function getMemberAddress($map){
		
		$model = M('Address');
		$data  = $model->where($map)->select();
		$mem   = M('Member')->find($map['userid']);
		$html  = '<select name="addressid" id="addressid" style="width:200px;"><option value="">请选择会员地址</option>';
		
		if($mem['longitude'] && $mem['latitude'] && $mem['address']){
			//$html .= '<option value="-1">'.$mem['address'].'</option>';
		}
		foreach($data as $k=>$v){
			$html .= '<option value="'.$v['id'].'">'.$v['address'].'</option>';
		}
		$html .= '</select>';
		
		return $html;
	}
	
	/**
	 * 计算餐厅到客户之间的距离以及时间和服务费
	 */
	public function getDevice($map){
		
		$model = D('Outlet');
		$view  = sendRest('BDC/Outlet/detail',array('id'=>$map['restid']));
		
		$list   = $model->getOutletArray($map);
		$array  = $model->getTime($view['data'],$list,$map);
		
		return $array;
	}
	
	//处理订单地址
	public function address_deal($user,$data){
		
		$model['mobile']   = $data['mobile'];
		$model['username'] = $data['username'];
		$model['address']  = $data['ads'].$data['detail'];
		
		if($model['dataid']){
			$model['tableid']  = 'Member';
			$model['dataid']   = $model['dataid'];
		}else{
			$model['tableid']  = $user['type'];
			$model['dataid']   = $user['id'];
		}
		
		if($data['addressid']){
			$model['tableid']  = 'Member';
			$model['dataid']   = $data['dataid'];
			if($data['addressid'] == -1){
				$member = M('Member')->find($data['dataid']);
				$model['address']  = $member['address'];
			}else{
				$one = M('Address')->find($data['addressid']);
				$model['address']  = $one['address'];
			}
		}else{
			if($data['email']){
				$member = M('Member')->where("username='".$data['email']."'")->find();
				if(!$member['id']){
					$map['username'] = $data['email'];
					$map['solevar']  = create_id();
					$map['isreg']    = 2;
					$map['email']    = $data['email'];
					$map['realname'] = $data['username'];
					$map['address']  = $data['ads'].$data['detail'];
					$map['mobile']   = $data['mobile'];
					$map['addtime']  = time();
					$map['remark']   = $data['remark'];
					$member['id']    = M('Member')->add($map);
				}
			}else{
				$email = $this->getNewEmail();
				$map['username'] = $email;
				$map['solevar']  = create_id();
				$map['isreg']    = 2;
				$map['email']    = $email;
				$map['realname'] = $data['username'];
				$map['address']  = $data['ads'].$data['detail'];
				$map['mobile']   = $data['mobile'];
				$map['addtime']  = time();
				$map['remark']   = $data['remark'];
				$member['id']    = M('Member')->add($map);
			}

			if($_POST['addid']){
				$site = M('Site')->find($_POST['addid']);
				$data['pointlng']  = $site['longitude'];
				$data['pointlat']  = $site['latitude'];
				$data['addressid'] = $site['id'];
			}

			$mem['userid']    = $member['id'];
			$mem['tableid']   = 'Member';
			$mem['realname']  = $data['username'];
			$mem['mobile']    = $data['mobile'];
			$mem['city']      = $data['cityid'];
			$mem['address']   = $data['ads'].$data['detail'];
			$mem['ads']       = $data['ads'];
			$mem['detail']    = $data['detail'];
			$mem['addtime']   = time();
			$mem['addressid'] = $data['addressid'];
			$mem['longitude'] = $data['pointlng'];
			$mem['latitude']  = $data['pointlat'];
			$detail = $mem;
			M('Address')->add($mem);
			
			$model['tableid']  = 'Member';
			$model['dataid']   = $member['id'];
		}

		//转移购物车
		$this->checkMemberCart($model['dataid']);
		return $model;
	}

	//生成一个新会员的邮箱账号
	public function getNewEmail(){
		$id = M('Member')->max('id');
		$id = $id+1;
		return "kkr".$id."@kkrabbit.com";
	}
	
	//转移购物车
	public function checkMemberCart($userid){
		$mem = getMemberSession();
		
		$where['tableid'] = $mem['tableid'];
		$where['dataid']  = $mem['dataid'];
		$map['tableid']   = 'Member';
		$map['dataid']    = $userid;
		
		M('Cart')->where($where)->save($map);
	}
	
	/**
	 * 添加订单
	 * @param array $map
	 */
	public function addOrder($array){
		
		$_POST  = $array; 
		$user   = getMemberSession();

		//处理购物车商品数量
		$ordcart = M('Cart');
		$pronum  = $array['pronum'];
		foreach($pronum as $a=>$b){
			$detail = $ordcart->find($a);
			$rows['id']  = $a;
			$rows['num'] = $b;
			$rows['xjprice'] = $b * $detail['price'];
			$ordcart->save($rows);
		}
		
		//处理地址
		$model  = $this->address_deal($user,$_POST);
			
		//处理时间
		$time       = $_POST['servetime'];   //所需时间
		$dishestime = $_POST['dishestime'];  //菜品所需时间
		$timeduan   = $this->getedltime($time,$dishestime);
		$model['sdltime'] = $timeduan['now'];
		$model['edltime'] = $timeduan['after'];
		
		//将数组转成json字符串
		$model['mobile']        = $_POST['mobile'];
		$model['username']      = $_POST['username'];
		$model['isdrink']       = $_POST['isdrink'];
		$model['isinvoice']     = $_POST['isinvoice'];
		$model['isprint']       = $_POST['isprint'];
		$model['isconfirm']     = $_POST['isconfirm'];
		$model['addressid']     = $_POST['addid'];
		$model['remark']        = $_POST['remark'];
		$model['content']       = $_POST['content'];
		$model['city']          = $_POST['cityid'];
		$model['outletid']      = $_POST['outletid'];
		$model['shipfee']       = $_POST['servefee'];
		$model['memaddid']      = $_POST['memaddid'];
		$model['orderno']       = createOrderNo();
		$model['ordertime']     = time();
		$model['status']        = 2;
		$model['invoice_title'] = $_POST['invoice_title']; //发票抬头
		$model['isyuding']      = 2;//是否预定餐，1是2否
		$model['admin']         = 1;//标识为后台添加的订单  1后台2前台
		
		$map['dataid']   = $model['dataid'];
		$map['outletid'] = $_POST['outletid'];
		$map['admin']    = 1;
		$cart = sendRest("RMS/Cart/view",$map);
		Log::write('addOrder:cart'.var_export($cart['data'],true),Log::DEBUG);
		$data = $cart['data'];
			
		//餐厅信息
		$outlet = sendRest('BDC/Outlet/detail',array('id'=>$_POST['outletid']));
		$outlet = $outlet['data'];//获取餐厅信息
		
		//计算用户购物车中商品总价格
		$total  = $this->get_tprice_total($data,$outlet);
		$status = $this->get_outlet_timestamp($outlet['data'],$model,$total);
		
		//根据优惠时间段计算订单金额
		$model = $this->get_order_total($status,$total,$model);
		Log::write('addOrder:'.var_export($model,true),Log::DEBUG);
		return sendRest("OMS/Order/add",$model,"post");
	}
	
	/**
	 * 计算总价，特价商品不参与餐厅折扣
	 */
	public function get_tprice_total($data,$coupon){
	
		$array  = $this->get_price_type($data);   //获取菜品饮品数组
		$dishes = $this->count_price($array['dishes'], $coupon['coupon']); //计算菜品价格
		$drink  = $this->count_price($array['drink'],  $coupon['coupon']); //计算饮品价格
		$total  = $this->count_order_price($dishes,$drink);      //计算菜品和饮品总价
	
		return $total;
	}
	
	/**
	 * 根据类型将数组分割成两个不同的数组
	 */
	private function get_price_type($data){
	
		$arr = $data['list'];
	
		foreach ($arr as $k => $v){
			if($v['flag']=="dishes"){
				$array['dishes'][] = $v;
			}else{
				$array['drink'][]  = $v;
			}
		}
		return $array;
	}
	
	/**
	 * 计算订单金额,不加服务费
	 * @param unknown_type $data
	 */
	private function count_order_price($dishes,$drink){
	
		$dishes_total_dprice  = $dishes['total_dprice'];
		$dishes_total_tprice  = $dishes['total_tprice'];
		$dishes_total_yhprice = $dishes['total_yhprice'];
		$dishes_totalfee      = $dishes['totalfee'];
		$dishes_settlefee     = $dishes['settlefee'];
	
		$drink_total_dprice   = $drink['total_dprice'];
		$drink_total_tprice   = $drink['total_tprice'];
		$drink_total_yhprice  = $drink['total_yhprice'];
		$drink_totalfee       = $drink['totalfee'];
		$drink_settlefee      = $drink['settlefee'];
	
		//$data['total_dprice']    = $dishes_total_dprice  + $drink_total_dprice;  //商品总金额
		$data['total_tprice']    = $dishes_total_tprice  + $drink_total_tprice;	   //商品特价总金额
		$data['total_yhprice']   = $dishes_total_yhprice + $drink_total_yhprice;   //优惠总金额
		$data['dishes_totalfee'] = $dishes_totalfee;                               //菜品总金额
		$data['drink_totalfee']  = $drink_totalfee;								   //酒水饮料总金额
		$data['settlefee']       = $dishes_settlefee;                              //成本总金额
		$data['receivefee']      = $data['total_tprice']- $data['settlefee'];	   //实收金额
	
		return $data;
	
	}
	
	/**
	 * 根据优惠时间段计算订单金额
	 * @param unknown_type $sdltime
	 * @param unknown_type $obegin
	 * @param unknown_type $oend
	 * @param unknown_type $total
	 * @param unknown_type $dlivery
	 * @param unknown_type $model
	 * @return Ambigous <number, unknown>
	 */
	public function get_order_total($status,$total,$model){
	
		$dlivery = $model['shipfee'];//获取服务费
		$dlivery = $dlivery>=0?$dlivery:0;
		
		$sdltime   = $model['sdltime'];
		$is_exempt = I("is_exempt");
		
		$model['cardfee']    = $total['total_yhprice'];           //优惠总金额
		$model['dishesfee']  = $total['dishes_totalfee'];         //菜品总金额
		$model['drinkfee']   = $total['drink_totalfee'];          //酒水饮料总金额
		$model['settlefee']  = $total['settlefee'];               //成本总金额
		$model['receivefee'] = $total['receivefee']+ $dlivery;    //实收金额
		$model['orderfee']   = $total['total_tprice'] + $dlivery; //实际支付金额
		
		if($status['status']==1){
			$model['exemptfee']  = $status['price'];       //减免的费用
		}else{
			$model['receivefee'] = $model['receivefee']+$status['price'];
			$model['orderfee']   = $model['orderfee']+$status['price'];
			$model['shipfee']    = $dlivery+$status['price']; //如果不是减免时间段，则加上服务费
		}
		
		return $model;
	}
	
	/**
	 * 计算价格
	 * @param unknown_type $data
	 */
	private function count_price($data,$coupon){
		
		$total_dprice   = 0;   //没有打折或者没有特价时的商品总价
		$total_tprice   = 0;   //商品特价或者折扣后的总价
		$total_yhprice  = 0;   //打折或者特价商品的优惠总价
		$totalfee       = 0;   //菜品或者酒水饮料总金额
		$settlefee      = 0;   //成本总价格
		
		$coupons = $coupon/100; //获取折扣如 0.98 = 98/100
		foreach ($data as $k => $v){
			if($v['isspec']==1){
			    
				$yhprice  = $v['dprice']-$v['tprice'];  //单件商品优惠价格  = 商品原价 - 商品特价
				$yhprices = $yhprice*$v['num'];         //商品优惠总价         = 商品优惠价格 * 商品数量
				
				$total_yhprice += $yhprices;  
				$total_tprice  += $v['xjprice'];
				$total_dprice  += $total_yhprice+$v['xjprice'];
				
			}else{
				if($coupon){
					$zkprice = $v['xjprice']*$coupons;   //折扣价格 = 小计*折扣比例
					$totals  = $v['tprice']*$coupons;
					
					$total_tprice  += $zkprice;
					$total_dprice  += $v['xjprice'];
					$total_yhprice += $total_dprice-$total_tprice;
				}else{
					$total_tprice  += $v['xjprice'];
					$total_dprice  += $v['xjprice'];
					$total_yhprice += $total_dprice-$total_tprice;
				}
			}
			$settlefee += $v['mprice']*$v['num']+$v['psPrice'];
			
		}
		
		$datas['total_dprice']  = $total_dprice;
		$datas['total_tprice']  = $total_tprice;
		$datas['total_yhprice'] = $total_yhprice;
		
		$datas['totalfee']      = $total_tprice;
		$datas['settlefee']     = $settlefee;
		return $datas;
		
	}
	
	/**
	 * 将餐厅免配送费的时间段转换成时间戳
	 */
	public function get_outlet_timestamp($map,$model,$total){
	
		$week    = explode(',',$map['week']); //餐厅选择的星期数组
		$nowweek = date('w');                 //获取当前星期几
		$sdltime = $model['sdltime'];         //配送时间
		$status  = -1;                        //返回状态
		
		$begin   = strtotime(date("Y-m-d")." ".$map['exemptbegin']); //餐厅免配送费开始时间 
		$end     = strtotime(date("Y-m-d")." ".$map['exemptend']);   //餐厅免配送费结束时间
		$nowweek = $nowweek!=0?$nowweek:7;  //英文版date获取到的星期天为0，这里要转化一下
		
		if($total['total_tprice']>=50){
			if($map['is_exempt']==1){
				if(in_array($nowweek, $week)){
					if($sdltime>=$begin&&$sdltime<=$end){
						$status = 1;
					}
				}
			}
		}
		
		return array('status'=>$status,'price'=>$map['exemptprice']);
	}
	
	//根据当前时间获取后面的时间
	public function getedltime($times,$dishestime){
	
		$ss    = intval($times+$dishestime)*60;
		$now   = time();
		$after = $ss+$now;
	
		return  array("now"=>$now,"after"=>$after);
	}
	
public function getHtml($id){
	
		//订单信息
		$json = sendRest("OMS/Order/detail",array("id"=>$id));
	
		//餐厅信息
		$outletid = $json['data']['outletid'];
		$outlet   = sendRest("BDC/Outlet/detail",array("id"=>$outletid));
	
		//订单详情信息
		$map['orderno'] = $json['data']['orderno'];
		$data = sendRest("OMS/Order/dlist",$map);
	
		$totalPrice = 0;
		foreach($data['data'] as $k=>$v){
			$totalPrice += $v['price']*$v['amount'];
			$data['data'][$k]['attr'] = json_decode($v['attr'],true);
			if($v['flag']=="dishes"){
				$cat['id'] = $v['pid'];
				$view = sendRest("RMS/Product/dishesDetail",$cat);
				$data['data'][$k]['detail']         = $view['data'];
				$data['data'][$k]['detail']['gnfr'] = json_decode($view['data']['gnfr'],true);
			}
		}
	
		$dlist  = $data['data'];
		$detail = $json['data'];
		$outlet = $outlet['data'];
	
		$html .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
		$html .= '<html xmlns="http://www.w3.org/1999/xhtml">';
		$html .= '<head>';
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		$html .= '<title>回执</title>';
		$html .= '</head>';
		$html .= '<body style="overflow-y:scroll;">';
		$html .= '<table style="font-size:10px;";  class="print"  width="100%" border="0" cellpadding="0" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<td class="title" align="center" style="font-size:22px;">K.K.RABBIT FOOD DELIVERY SERVICE</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td class="website" align="center" style="font-size:16px;">www.kkrabbit.com.cn</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td class="telephone" align="center" style="font-size:16px;">Tel:400-020-1717&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax:(021)5239-9205</td>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		$html .= '<tr>';
		$html .= '<td>';
		$html .= '<table style="padding-top:20px;vertical-align:center;" class="print_table1" width="100%" border="0" cellpadding="0" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th></th>';
		$html .= '<td></td>';
		$html .= '<th class="odd"></th>';
		$html .= '<td></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td width="110" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td width="220" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td class="space" style=" height:1px;border-left: 1px solid #333333;border-top: 1px solid #333333;"></td>';
		$html .= '<td width="110" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th style="" width="110">Delivery To:<br/>客户名称：</th>';
		//$html .= '<td style="" width="220">'.$detail['username'].'</td>';
		$html .= '<td style="" width="220">*********</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th style=" " width="110" class="odd">Order No:<br/>订单号：</th>';
		$html .= '<td style="">'.$detail['orderno'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>Mobile:<br/>电话：</th>';
		//$html .= '<td>'.$detail['mobile'].'</td>';
		$html .= '<td>*********</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Order Date:<br/>订单日期：</th>';
		$html .= '<td>'.date('m/d',$detail['addtime']).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>Address:<br/>地址：</th>';
		$html .= '<td>'.$detail['address'].'</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Order Time:<br/>订餐时间：</th>';
		$html .= '<td>'.date('m/d H:i:s',$detail['addtime']).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2"></td>';
		$html .= '<td colspan="3" class="space" style="border-left: 1px solid #333333; height:5px;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th>&nbsp;</th>';
		$html .= '<td>&nbsp;</td>';
		$html .= '<td style="border-left: 1px solid #333333; width:10px;"></td>';
		$html .= '<th class="odd" style="">Target Delivery:<br/>配送时间：</th>';
		$html .= '<td>'.date('m/d H:i',$detail['sdltime']).'&nbsp;&nbsp;~&nbsp;&nbsp;'.date('m/d H:i',$detail['edltime']);
	
		if($detail['isyuding']==1){
			$html .= '（预定餐）';
		}
	
		$html .= '</td></tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2" style=" height:1px;border-bottom: 1px solid #333333;"></td>';
		$html .= '<td colspan="3" class="space" style=" height:1px;border-left: 1px solid #333333;border-bottom: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '<td  class="space" style=" height:1px;border-top: 1px solid #333333;"></td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<th style="">Restaurant:</th>';
		$html .= '<td style="">'.$outlet['entitle'].'</td>';
		$html .= '<td style="width:10px;"></td>';
		$html .= '<th style="" class="odd">餐厅：</th>';
		$html .= '<td style="">'.$outlet['title'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td colspan="2" style=" height:1px;"></td>';
		$html .= '<td colspan="3" class="space" style=" height:1px;"></td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '<table class="print_table2" width="100%" border="0" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Item ID<br/>编号</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Item<br/>菜名</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Quantity<br/>数量</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Property<br/>属性</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Unit Price<br/>单价</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333;">Comment<br/>要求</th>';
		$html .= '<th style="border-bottom: 1px solid #333333;border-top: 1px solid #333333; text-algin:right;" class="right">Price<br/>总价</th>';
		$html .= '</tr>';
		$html .= '</thead><style>body{line-height:1;}</style>';
		$html .= '<tbody>';
	
	
		//菜品饮品开始
		foreach($dlist as $k=>$v){
			if($v['flag']=='dishes'){
				$html .= '<tr>';
				$html .= '<td style="">'.$v['pno'].'</td>';
				$html .= '<td style="">'.$v['title'].'<br/>'.$v['entitle'].'</td>';
				$html .= '<td  align="center" style="">'.$v['amount'].'</td>';
				$html .= '<td style="">';
					
				if($v['attr']){
					foreach($v['attr'] as $l=>$m){
						$html .= '<span class="entitle">'.$m['title'].'（'.$m['entitle'].'）：</span>';
							
						foreach($m['config'] as $d=>$n){
							$html .= '<span>'.$n['title'].'（'.$n.entitle.'）';
							if($n['num']){
								$html .= '（'.$n['num'].'份/portion）';
							}
							$html .= '</span>';
						}
						$html .= '<br/>';
					}
				}
					
				$html .= '</td>';
				$html .= '<td style="">￥'.$v['price'].'</td>';
				$html .= '<td style="">'.$v['content'].'</td>';
				$html .= '<td style="text-algin:right;" class="right">￥'.$v['total'].'</td>';
				$html .= '</tr>';
			}
		}
	
		$html .= '<tr>';
		$html .= '<td colspan="5"></td>';
		$html .= '<td colspan="2" class="total right" style="border-top:2px solid #000"><span>SubTotal/小计：</span>￥'.number_format($detail["dishesfee"]+$detail['cardfee'],2).'</td>';
		$html .= '</tr>';
	
		$html .= '<tr><td colspan="7" style="border-top:1px solid #000"></td></tr>';
		$num   = 0;
		
		foreach($dlist as $k=>$v){
			if($v['flag']=='drink'){
				$html .= '<tr>';
				$html .= '<td style="">'.$v['pno'].'</td>';
				$html .= '<td style="">'.$v['title'].'<br/>'.$v['entitle'].'</td>';
				$html .= '<td style="">';
					
				if($v['attr']){
					foreach($v['attr'] as $l=>$m){
						$html .= '<span class="entitle">'.$m['title'].'（'.$m['entitle'].'）：</span>';
							
						foreach($m['config'] as $d=>$n){
							$html .= '<span>'.$n['title'].'（'.$n.entitle.'）';
							if($n['num']){
								$html .= '（'.$n['num'].'份/portion）';
							}
							$html .= '</span>';
						}
						$html .= '<br/>';
					}
				}
					
				$html .= '</td>';
				$html .= '<td  align="center" style="">'.$v['amount'].'</td>';
				$html .= '<td style="">￥'.$v['price'].'</td>';
				$html .= '<td style="">'.$v['content'].'</td>';
				$html .= '<td style="text-algin:right;" class="right">￥'.$v['total'].'</td>';
				$html .= '</tr>';
				$num  ++;
			}
		}
		
		if($num>0){
			$html .= '<tr>';
			$html .= '<td colspan="5"></td>';
			$html .= '<td colspan="2" class="total right" style="border-buttom:1px solid #FFF;border-top:2px solid #000">';
			$html .= '<span>SubTotal/小计：</span>￥'.$detail['drinkfee'];
			$html .= '</td>';
			$html .= '</tr>';
			$html .= '<tr><td colspan="7" style="border-top:1px solid #000"></td></tr>';
		}
		//菜品饮品结束
	
		$html .= '</tbody>';
		$html .= '</table>';
		$html .= '<table class="print_table3" width="100%" border="0" cellpadding="3" cellspacing="0">';
		$html .= '<tr>';
		$html .= '<td>Memo:<br/>备注：</td>';
		$html .= '<td width="225">'.$detail['content'].'</td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Restaurant Total:<br/>餐厅金额</td>';
		$html .= '<td class="right">￥'.number_format($detail['dishesfee']+$detail['cardfee'],2).'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td rowspan="4" style="width:225px;">';
		$html .= '<div>';
		
		$drink = C('IS_SEND_DRINK');
		if($detail['isdrink']){
			$html .= '免费饮品：'.$drink[$detail['isdrink']]['zh-cn'].'（'.$drink[$detail['isdrink']]['en-us'].'）';
		}
		if($detail['isinvoice']==1){
			$html .= '发票：抬头（'.$detail['invoice_title'].'）';
		}
		
		$html .= '</div>';
		$html .= '</td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Adjustment:<br/>调整费：</td>';
		$html .= '<td class="right">￥'.$detail['b_price'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Service Charge:<br/>服务费：</td>';
		$html .= '<td class="right">￥'.$detail['shipfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Wine & Drink:<br/>酒饮料： </td>';
		$html .= '<td class="right">￥'.$detail['drinkfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tr>';
		$html .= '<td></td>';
		$html .= '<td class="dercoration" style="text-decoration: underline;">Discount:<br/>优惠：</td>';
		$html .= '<td class="right">-￥'.$detail['cardfee'].'</td>';
		$html .= '</tr>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td colspan="2"  style="width:385px;"></td>';
		$html .= '<td class="o_total dercoration" style="text-decoration: underline;">Order Total:<br/>总价：</td>';
		$html .= '<td class="right o_total">￥'.number_format($detail["orderfee"]+$detail['b_price'],2).'</td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '</td>';
		$html .= '</tr>';
		$html .= '</tbody>';
		$html .= '<tfoot>';
		$html .= '<tr>';
		$html .= '<td class="print_foot" style="text-align:right;">'.date("Y-m-d H:i:s").'</td>';
		$html .= '</tr>';
		$html .= '</tfoot>';
		$html .= '</table>';
		$html .= '</body>';
		$html .= '</html>';
	
		return $html;
	}

	//根据选择的地址获取该地址周围的餐厅列表
	public function getOutletArray($map){
		
		//查询地址附近的餐厅列表
		$poit = $map['pointlng'].",".$map['pointlat'];
		$list = mapNearby(array("location"=>$poit));
		
		//查询数据库中餐厅列表餐厅列表
		if($map['keywords']){
			$where['title|entitle'] = array('like','%'.$map['keywords'].'%');
		}
		if($map['cuisine']){
			$where['cuisine'] = array('like','%'.$map['cuisine'].'%');
		}
		$where['isdel']  = 2;
		$where['isrest'] = array('neq',1);
		$where['cityid'] = $map['cityid'];
		$field = "id,title,entitle,starthours,starthours1,endhours,endhours1,is_tingye,is_tigong,city";
		$data = M('Outlet')->where($where)->field($field)->select();
		Log::write('getOutletArray:'.M('Outlet')->getLastSql(),Log::DEBUG);
			
		$array = array();
		if($data){
			foreach($list as $k=>$v){
				foreach($data as $m=>$n){
					if($v['outletid'] == $n['id'] && $n['city']==$map['cityid']){
						$array[$n['id']]['id']       = $n['id'];
						$array[$n['id']]['title']    = $n['title'];
						$array[$n['id']]['entitle']  = $n['entitle'];
						$array[$n['id']]['distance']    = $v['distance'];
						$array[$n['id']]['starthours']  = $n['starthours'];
						$array[$n['id']]['starthours1'] = $n['starthours1'];
						$array[$n['id']]['endhours']    = $n['endhours'];
						$array[$n['id']]['endhours1']   = $n['endhours1'];
						$array[$n['id']]['is_tingye']   = $n['is_tingye'];
						$array[$n['id']]['is_tigong']   = $n['is_tigong'];
						continue;
					}
				}
			}
		}
		
		$html = "<option value=''>请选择餐厅</option>";
		foreach($array as $k=>$v){
			$css   = $this->getRestaurantTime($v);
			$html .= "<option style='$css' fapiao='".$v['is_tigong']."' value='".$k."'>".$v['title']."/".stripcslashes($v['entitle'])."/（".$v['distance']."米）</option>";
		}
		return $html;
	}

		//更新订单详情商品数量
	public function editOrderDetailNum($data){
		
		$model  = M('OrderDetail');
		$detail = $model->find($data['detailid']);
		$where  = array('orderno'=>$data['orderno']);
		
		if($detail['id']){
		
			//先更新商品数量
			$map['id']      = $detail['id'];
			$map['amount']  = $data['amount'];
			//$map['mprice']  = $detail['mprice']/$detail['amount']*$data['amount'];
			//$map['smprice'] = $detail['smprice']/$detail['amount']*$data['amount'];
			$map['total']   = $detail['price']*$data['amount'];
			$map['amount']  = $data['amount'];
			$model->save($map);
			
			//更新订单总价
			$total = $this->caleOrderTotal($where);
			
			if($total){
				return array('status'=>1);
			}else{
				return array('info'=>'商品数量更新失败，请稍后重试');
			}
		}else{
			return array('info'=>'非法操作');
		}
	}
	
	//根据订单详情计算订单总价
	public function caleOrderTotal($where){
		
		$model = M('Order');
		$order = $model->where($where)->find();
		$list  = M('OrderDetail')->where($where)->select();
		
		$orderfee   = 0; //订单总金额（dishesfee+drinkfee+shipfee）
		$drinkfee   = 0; //酒水饮料总金额
		$dishesfee  = 0; //菜品总价格（订餐金额）
		$shipfee    = $order['shipfee']; //订单配送金额
		$settlefee  = 0; //结算金额（成本价总金额）
		$receivefee = 0; //实收金额（总金额-结算金额）
		
		foreach($list as $k=>$v){
			if($v['flag'] == 'dishes'){
				$dishesfee += $v['total'];
			}else{
				$drinkfee  += $v['total'];
			}
			$settlefee += ($v['mprice']+$v['smprice'])*$v['amount'];
		}
		
		$total['id'] = $order['id'];
		$total['orderfee']   = $dishesfee + $drinkfee + $shipfee;
		$total['drinkfee']   = $drinkfee;
		$total['dishesfee']  = $dishesfee;
		$total['settlefee']  = $settlefee;
		$total['receivefee'] = $total['orderfee'] - $settlefee;
		
		return $model->save($total);
	}
}
?>